package com.tomcov.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.google.gwt.user.client.Window;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.tomcov.client.service.MapService;
import com.tomcov.shared.Journey;
import com.tomcov.shared.JourneyPassenger;
import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.Geometry;
import com.vividsolutions.jts.geom.GeometryFactory;
/*
 * Pour cette algorithme, je me suis basé sur le travail de mon ex binome. J'ai quand même contribuer un tant soit peu
 * a l'autre projet avant de me faire virer comme un malpropre. Je me suis donc permis de réutiliser ces quelques lignes
 * en les adaptants a ma sauce.
 */

public class MapServiceImpl extends RemoteServiceServlet implements MapService{

	private static final long serialVersionUID = 1L;

	public Coordinate[] stepToCoor(Journey J){
		List<String> coordinates = J.getStepsDetails();
		Coordinate[] coordArray2 = new Coordinate[coordinates.size()];
		int i = 0;
		for (String singleCoord : coordinates) {
			Coordinate coord = new Coordinate(Double.parseDouble(singleCoord
					.split(",")[0]),
					Double.parseDouble(singleCoord.split(",")[1]));
			coordArray2[i] = coord;
			i++;
		}
		return coordArray2;
	}

	public List<JourneyPassenger> chercheurPassager(ArrayList<Journey> add,Journey J,List<JourneyPassenger> results){
		Coordinate[] array2 = stepToCoor(J);
		Geometry buffer = new GeometryFactory().createLineString(array2);
		List<JourneyPassenger> JourneyCorrespondant =new ArrayList<JourneyPassenger> ();
		for (JourneyPassenger travel : results) {
			List<String> stepsDetails = J.getStepsDetails();
			Coordinate[] arrayWaypoints = null;
			if (J.getWaypoints() != null) {
				stepsDetails.addAll(J.getWaypoints());
				arrayWaypoints = new Coordinate[J.getWaypoints().size()];
				int k = 0;
				for (String singleCoord : J.getWaypoints()) {
					Coordinate coord = new Coordinate(
							Double.parseDouble(singleCoord.split(",")[0]),
							Double.parseDouble(singleCoord.split(",")[1]));
					arrayWaypoints[k] = coord;
					k++;
				}
			}
			int i = 0;
			Coordinate[] coordArray = new Coordinate[stepsDetails.size()];
			for (String singleCoord : stepsDetails) {
				Coordinate coord = new Coordinate(
						Double.parseDouble(singleCoord.split(",")[0]),
						Double.parseDouble(singleCoord.split(",")[1]));
				coordArray[i] = coord;
				i++;
			}
			List<String> steps = J.getSteps();
			int j = 0;
			Coordinate[] array = new Coordinate[steps.size()];
			for (String singleCoord : steps) {
				Coordinate coord = new Coordinate(
						Double.parseDouble(singleCoord.split(",")[0]),
						Double.parseDouble(singleCoord.split(",")[1]));
				array[j] = coord;
				j++;
			}
			Geometry geom = new GeometryFactory().createLineString(coordArray);
			if (geom.buffer(J.getDetour() / 111).contains(buffer)) {
				float distance = 0;
				float duration = 0;
				try {
					String urlString = "http://routes.cloudmade.com/8ee2a50541944fb9bcedded5165f09d9/api/0.3/"
						+ array[0].x + "," + array[0].y + ",%5B";
					for (int l = 0; l < arrayWaypoints.length; l++) {
						urlString += arrayWaypoints[l].x + ","
						+ arrayWaypoints[l].y + ",";
					}
					urlString = urlString.substring(0, urlString.length() - 2);
					urlString += "%5D," + array[array.length - 1].x + ","
					+ array[array.length - 1].y + "/car/fastest.gpx";
					URL url = new URL(urlString);
					BufferedReader reader = new BufferedReader(
							new InputStreamReader(url.openStream()));
					String line;
					if ((line = reader.readLine()) != null) {
						line = line.substring(line.indexOf("distance") + 9);
						distance = Float.valueOf(line.substring(0,
								line.indexOf("<")));
						line = line.substring(line.indexOf("time") + 5);
						duration = Float.valueOf(line.substring(0,
								line.indexOf("<")));
					}
				} catch (MalformedURLException e) {

				} catch (IOException e) {
				}
				if (travel.getHeureArr().getTime() <= J.getHeureArr().getTime()
						&& travel.getHeuredep().getTime() >= J.getHeuredep().getTime()
						&& (travel.getDistance() - distance) <= J.getDetour()
						&& (new Date(travel.getHeuredep().getTime()+ (long) (duration * 1000))).getTime() 
						<= travel.getHeureArr().getTime()) {
					travel.getSteps();
					JourneyCorrespondant.add(travel);
				}
			}
		}
		return JourneyCorrespondant;
	}

	public List<Journey> chercheurDriver(ArrayList<Journey> add,JourneyPassenger J, List <Journey> results){

		List<String> coordinates = J.getStepsDetails();
		Coordinate[] array = new Coordinate[coordinates.size()];
		int ii2 = 0;
		for (String singleCoord : coordinates) {
			Coordinate coord = new Coordinate(Double.parseDouble(singleCoord
					.split(",")[0]),
					Double.parseDouble(singleCoord.split(",")[1]));
			array[ii2] = coord;
			ii2++;

		}
		List<Journey> JourneyCorrespondant = new ArrayList<Journey> ();
		for (Journey travel : results) {
			Coordinate[] coordArray = stepToCoor(travel);
			Geometry buffer = new GeometryFactory().createLineString(coordArray);
			if (buffer.contains(new GeometryFactory().createMultiPoint(coordArray))) {
				float distance = 0;
				float duration = 0;
				try {
					URL url = new URL(
							"http://routes.cloudmade.com/911fb86a02cd41c0b8a91688c1c05dfa/api/0.3/"
							+ array[0].x + "," + array[0].y + ",%5B"
							+ coordArray[0].x + "," + coordArray[0].y
							+ "," + coordArray[coordArray.length - 1].x
							+ "," + coordArray[coordArray.length - 1].y
							+ "%5D," + array[array.length - 1].x + ","
							+ array[array.length - 1].y
							+ "/car/fastest.gpx");
					BufferedReader reader = new BufferedReader(
							new InputStreamReader(url.openStream()));
					String line;
					if ((line = reader.readLine()) != null) {
						System.out.println("line = "+line);
						line = line.substring(line.indexOf("distance") + 9);
						System.out.println("line = "+line);
						distance = Float.valueOf(line.substring(0,line.indexOf("<")));
						line = line.substring(line.indexOf("time") + 5);
						System.out.println("line = "+line);
						duration = Float.valueOf(line.substring(0,line.indexOf("<")));
					}
					else{
						Window.alert("ca marche pas");
						System.out.println("ca marceh pas");
					}
				} catch (MalformedURLException e) {

				} catch (IOException e) {
				}
				if (travel.getHeureArr().getTime() <= J.getHeureArr().getTime()
						&& travel.getHeuredep().getTime() <= J.getHeurede2().getTime()
						&& distance <= (travel.getDetour() + travel.getDistance())
						&& (J.getHeuredep().getTime() + (long) (duration * 1000)) <= J.getHeureArr().getTime())
					JourneyCorrespondant.add(travel);
			}
		}
		return JourneyCorrespondant;
	}
	
}